<template>
    <el-dialog :title="title" v-model="dialogVisible" width="700px" destroy-on-close @close="handleClose"
        append-to-body>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="字典值" prop="value">
                <el-input v-model="form.value" placeholder="请输入字典值" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
                <el-input-number v-model="form.sort" :min="0" :max="999" />
            </el-form-item>
            <el-form-item label="状态">
                <el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="启用"
                    inactive-text="禁用" inline-prompt
                    style="--el-switch-on-color: var(--el-color-success); --el-switch-off-color: var(--el-color-danger)" />
            </el-form-item>

            <!-- 多语言表单 -->
            <el-divider>多语言配置</el-divider>
            <el-form-item v-for="(lang, index) in form.langs" :key="index" :label="'语言' + (index + 1)"
                :prop="'langs.' + index + '.name'" :rules="{
                    required: true,
                    message: '请输入字典项名称',
                    trigger: 'blur'
                }">
                <div class="lang-form-item">
                    <el-select v-model="lang.language_id" placeholder="请选择语言" style="width: 120px">
                        <el-option v-for="item in userStore.languages" :key="item.language_id" :label="item.name"
                            :value="item.language_id" />
                    </el-select>
                    <el-input v-model="lang.name" placeholder="请输入字典项名称" style="width: 200px; margin: 0 10px;" />
                    <el-input v-model="lang.remark" placeholder="请输入备注说明" style="width: 200px" />
                    <el-button type="danger" link :disabled="form.langs.length <= 1" @click="removeLang(index)">
                        <el-icon>
                            <Delete />
                        </el-icon>
                    </el-button>
                </div>
            </el-form-item>

            <!-- 添加语言按钮 -->
            <el-form-item>
                <el-button type="primary" link @click="addLang">
                    <el-icon>
                        <Plus />
                    </el-icon>添加语言
                </el-button>
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { addDictItem, editDictItem } from '/@/api/dict'
import type { DictItem, DictItemForm } from '/@/types/dict'
import { useUserStore } from '/@/store/modules/user'
import { useAclStore } from '/@/store/modules/acl'

const props = defineProps<{
    visible: boolean
    type: 'add' | 'edit'
    dictId: number
    currentRow?: DictItem | null
}>()

const emit = defineEmits(['update:visible', 'success'])
const userStore = useUserStore()
const aclStore = useAclStore()

const dialogVisible = computed({
    get: () => props.visible,
    set: (val) => emit('update:visible', val)
})

const title = computed(() => props.type === 'add' ? '新增字典项' : '编辑字典项')

const loading = ref(false)
const formRef = ref<FormInstance>()

// 默认表单数据
const defaultForm: DictItemForm = {
    dict_id: props.dictId,
    value: '',
    sort: 0,
    status: 1,
    langs: [
        {
            language_id: 1, // 默认添加中文
            name: '',
            remark: ''
        }
    ]
}

const form = reactive<DictItemForm>({ ...defaultForm })

// 表单校验规则
const rules = {
    value: [
        { required: true, message: '请输入字典值', trigger: 'blur' }
    ]
}

// 初始化表单数据
const initFormData = () => {
    if (props.type === 'edit' && props.currentRow) {
        const { value, sort, status, langs } = props.currentRow
        Object.assign(form, { value, sort, status })
        form.langs = langs.map(({ language_id, name, remark }) => ({
            language_id,
            name,
            remark
        }))
    } else {
        Object.assign(form, defaultForm)
        form.dict_id = props.dictId
        // 如果没有语言，使用默认语言
        if (form.langs.length === 0 && userStore.languages.length > 0) {
            form.langs.push({
                language_id: userStore.languages[0].language_id,
                name: '',
                remark: ''
            })
        }
    }
}

// 添加语言
const addLang = () => {
    form.langs.push({
        language_id: 0,
        name: '',
        remark: ''
    })
}

// 移除语言
const removeLang = (index: number) => {
    form.langs.splice(index, 1)
}

// 处理提交
const handleSubmit = async () => {
    // 检查权限
    if (props.type === 'add' && !aclStore.getPermission.includes('system:dictItem:doAdd')) {
        return
    }
    if (props.type === 'edit' && !aclStore.getPermission.includes('system:dictItem:doEdit')) {
        return
    }

    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
        if (valid) {
            loading.value = true
            try {
                if (props.type === 'add') {
                    await addDictItem(form)
                    ElMessage.success('新增成功')
                } else if (props.currentRow) {
                    await editDictItem(props.currentRow.item_id, form)
                    ElMessage.success('更新成功')
                }
                emit('success')
                handleClose()
            } catch (error) {
                console.error('提交失败:', error)
            } finally {
                loading.value = false
            }
        }
    })
}

// 处理关闭
const handleClose = () => {
    dialogVisible.value = false
    formRef.value?.resetFields()
}

// 监听visible变化
watch(() => props.visible, (val) => {
    if (val) {
        initFormData()
    }
})

// 监听dictId变化
watch(() => props.dictId, () => {
    if (props.type === 'add') {
        form.dict_id = props.dictId
    }
})
</script>

<style lang="scss" scoped>
.lang-form-item {
    display: flex;
    align-items: center;
}
</style>